from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Log
from .serializers import LogSerializer

class LogViewSet(viewsets.ModelViewSet):
    """
    系统日志视图集
    """
    queryset = Log.objects.all().order_by('-timestamp')
    serializer_class = LogSerializer
    permission_classes = [permissions.IsAuthenticated]

    def list(self, request, *args, **kwargs):
        """
        查询系统日志，支持按用户、模块、时间范围过滤
        """
        user = request.query_params.get('user')
        module = request.query_params.get('module')
        start_time = request.query_params.get('start_time')
        end_time = request.query_params.get('end_time')

        queryset = self.queryset
        if user:
            queryset = queryset.filter(user__icontains=user)
        if module:
            queryset = queryset.filter(module__icontains=module)
        if start_time and end_time:
            queryset = queryset.filter(timestamp__range=[start_time, end_time])

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['GET'])
    def detail(self, request, pk=None):
        """
        查看指定日志的详细信息
        """
        log = self.get_object()
        serializer = self.get_serializer(log)
        return Response(serializer.data)

    @action(detail=False, methods=['POST'])
    def export(self, request):
        """
        导出日志数据为文件
        """
        # 示例导出为 JSON，CSV 可自行扩展
        logs = self.queryset
        serializer = self.get_serializer(logs, many=True)
        return Response(serializer.data, content_type='application/json')

    @action(detail=False, methods=['GET'])
    def analyze(self, request):
        """
        分析日志数据，生成统计报表
        """
        # 示例统计模块访问次数
        analysis = Log.objects.values('module').annotate(count=models.Count('module'))
        return Response(analysis)

    @action(detail=False, methods=['GET'])
    def alerts(self, request):
        """
        获取系统实时异常警报信息
        """
        # 示例：模拟返回警报数据
        alerts = [{"message": "CPU Usage High", "level": "critical", "timestamp": "2024-12-13T00:00:00"}]
        return Response(alerts)
